use pest::Parser;
use pest_derive::Parser;
use std::collections::HashMap;

#[derive(Parser)]
#[grammar = "json.pest"]
pub struct JSONParser;

#[derive(Debug, PartialEq, Clone)]
pub enum JsonValue {
    String(String),
    Number(f64),
    Boolean(bool),
    Array(Vec<JsonValue>),
    Object(HashMap<String, JsonValue>),
    Null,
}

pub fn parse_json(input: &str) -> Result<JsonValue, pest::error::Error<Rule>> {
    let json_pair = JSONParser::parse(Rule::json, input)?.next().unwrap();
    let value_pair = json_pair.into_inner().next().unwrap();
    parse_value(value_pair)
}

fn parse_value(pair: pest::iterators::Pair<Rule>) -> Result<JsonValue, pest::error::Error<Rule>> {
    // value 规则内部包含实际的类型规则，我们需要深入一层
    let inner_pair = pair.into_inner().next().unwrap();
    
    match inner_pair.as_rule() {
        Rule::string => {
            let content = inner_pair.as_str();
            // 去掉引号
            let inner = &content[1..content.len()-1];
            Ok(JsonValue::String(inner.to_string()))
        },
        Rule::number => {
            let num_str = inner_pair.as_str();
            Ok(JsonValue::Number(num_str.parse().unwrap_or(0.0)))
        },
        Rule::boolean => {
            Ok(JsonValue::Boolean(inner_pair.as_str() == "true"))
        },
        Rule::null => {
            Ok(JsonValue::Null)
        },
        Rule::array => {
            let mut values = Vec::new();
            for value_pair in inner_pair.into_inner() {
                values.push(parse_value(value_pair)?);
            }
            Ok(JsonValue::Array(values))
        },
        Rule::object => {
            let mut map = HashMap::new();
            for pair in inner_pair.into_inner() {
                let mut inner_pairs = pair.into_inner();
                let key_pair = inner_pairs.next().unwrap();
                let value_pair = inner_pairs.next().unwrap();
                
                let key = parse_string_content(key_pair);
                let value = parse_value(value_pair)?;
                map.insert(key, value);
            }
            Ok(JsonValue::Object(map))
        },
        rule => {
            println!("遇到意外规则: {:?}", rule);
            println!("内容: {}", inner_pair.as_str());
            unreachable!("Unexpected rule: {:?}", rule)
        }
    }
}

// 辅助函数：解析字符串内容（去掉引号）
fn parse_string_content(pair: pest::iterators::Pair<Rule>) -> String {
    let content = pair.as_str();
    content[1..content.len()-1].to_string()
}

// 更好的显示实现
impl std::fmt::Display for JsonValue {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            JsonValue::String(s) => write!(f, "\"{}\"", s),
            JsonValue::Number(n) => write!(f, "{}", n),
            JsonValue::Boolean(b) => write!(f, "{}", b),
            JsonValue::Null => write!(f, "null"),
            JsonValue::Array(arr) => {
                write!(f, "[")?;
                for (i, item) in arr.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "{}", item)?;
                }
                write!(f, "]")
            }
            JsonValue::Object(obj) => {
                write!(f, "{{")?;
                for (i, (k, v)) in obj.iter().enumerate() {
                    if i > 0 { write!(f, ", ")?; }
                    write!(f, "\"{}\": {}", k, v)?;
                }
                write!(f, "}}")
            }
        }
    }
}

fn main() {
    println!("=== JSON 解析器测试 ===\n");

    // 先测试所有基本类型
    let test_cases = vec![
        (r#""hello world""#, "简单字符串"),
        ("123.45", "数字"),
        ("-42", "负数"),
        ("true", "布尔真"),
        ("false", "布尔假"),
        ("null", "null值"),
    ];

    for (json, description) in test_cases {
        println!("测试: {}", description);
        println!("输入: {}", json);
        match parse_json(json) {
            Ok(value) => println!("成功: {}", value),
            Err(e) => println!("错误: {}", e),
        }
        println!("---");
    }

    // 单独测试数组
    println!("\n=== 数组测试 ===");
    let array_tests = vec![
        r#"[]"#,
        r#"["a"]"#,
        r#"["a", "b"]"#,
        r#"["a", "b", "c"]"#,
        r#"[1, 2, 3]"#,
        r#"[true, false, null]"#,
    ];

    for array_json in array_tests {
        println!("输入: {}", array_json);
        match parse_json(array_json) {
            Ok(value) => println!("成功: {}", value),
            Err(e) => println!("错误: {}", e),
        }
    }

    // 单独测试对象
    println!("\n=== 对象测试 ===");
    let object_tests = vec![
        r#"{}"#,
        r#"{"name": "Alice"}"#,
        r#"{"name": "Alice", "age": 30}"#,
    ];

    for obj_json in object_tests {
        println!("输入: {}", obj_json);
        match parse_json(obj_json) {
            Ok(value) => println!("成功: {}", value),
            Err(e) => println!("错误: {}", e),
        }
    }

    // 测试复杂 JSON
    let complex_json = r#"{
        "name": "Alice",
        "age": 30,
        "isStudent": false,
        "hobbies": ["reading", "swimming"],
        "address": {
            "city": "Beijing",
            "postcode": "100000"
        },
        "scores": null
    }"#;

    println!("\n=== 复杂 JSON 测试 ===");
    println!("输入: (多行 JSON)");
    match parse_json(complex_json) {
        Ok(json_value) => {
            println!("解析成功:");
            println!("{}", json_value);
        }
        Err(e) => {
            println!("解析错误: {}", e);
            // 打印调试信息
            println!("\n调试信息:");
            if let Ok(pairs) = JSONParser::parse(Rule::json, complex_json) {
                for pair in pairs {
                    print_pair(pair, 0);
                }
            }
        }
    }
}

// 调试用的辅助函数
fn print_pair(pair: pest::iterators::Pair<Rule>, depth: usize) {
    let indent = "  ".repeat(depth);
    println!("{}{:?}: '{}'", indent, pair.as_rule(), pair.as_str());
    
    for inner_pair in pair.into_inner() {
        print_pair(inner_pair, depth + 1);
    }
}